﻿var timeout = 300;
var closetimer = null;
var openMenus = new Array();
$(document).ready(setupMenuEvents);

function setupMenuEvents() {
	$(".SubMenuParent").mouseenter(function(eventObj) {
		var t = $(this);
		var tparent = t.offsetParent(".SubMenu").prev(".SubMenuParent");
		closeMenus(tparent, t);
		addMenuInArray(t);
		var cm = t.next(".SubMenu");
		if (t.hasClass("HorzMenu"))
			cm.css("left", t.position().left + t.width()).css("top", t.position().top);
		if (cm.hasClass("fadeMenu"))
			cm.fadeIn("def");
		else if (cm.hasClass("slideMenu"))
			cm.slideDown("def");
		else if (cm.hasClass("toggleMenu"))
			cm.toggle("def");
		else
			cm.css("display", "block");
		menuItemOpen = true;
		eventObj.stopPropagation();
	}).mouseleave(function(eventObj) {
		var s = $(eventObj.relatedTarget).offsetParent(".SubMenu").prev(".SubMenuParent");
		var tp = $(this).offsetParent(".SubMenu").prev(".SubMenuParent");
		if (s.length == 0 || s.get(0) != tp.get(0)) {
			setMenuTimer();
		}
		else if (s.get(0) == tp.get(0)) {
			cancelTimer();
			closetimer = window.setTimeout(function() { closeMenus(tp); }, timeout);
		}
		else {
			closeMenus(s);
		}
	});
	$(".SubMenu").mouseenter(function(eventObj) {
		closeMenus($(this).prev(".SubMenuParent").eq(0));
		eventObj.stopPropagation();

	}).mouseleave(function(eventObj) {
		setMenuTimer();
	});
}

var menuItemOpen = false;
function setMenuTimer() {
	cancelTimer();
	closetimer = window.setTimeout("closeMenus()", timeout);
}
function closeMenus(inMenParent, inMen) {
	if (typeof inMenParent == "number")
		inMenParent = null;
	cancelTimer();
	for (var i = openMenus.length - 1; i >= 0; i--) {
		if (inMenParent == null || inMenParent== 0 || inMenParent.get(0) != openMenus[i].get(0)) {
			if (inMen != null && inMen.get(0) == openMenus[i].get(0))
				break;
			var cm = openMenus[i].next(".SubMenu");
			if (cm.hasClass("fadeMenu"))
				cm.fadeOut("def");
			else if (cm.hasClass("slideMenu"))
				cm.slideUp("def");
			else if (cm.hasClass("toggleMenu"))
				cm.toggle("def");
			else
				cm.css("display", "none");
			openMenus.pop();
		}
		else if (inMenParent.get(0) == openMenus[i].get(0))
			break;
	}
	if(openMenus.length == 0)
		menuItemOpen = false;

}
function cancelTimer() {
	if (closetimer) {
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}
function addMenuInArray(men) {
	for (var i = 0; i < openMenus.length - 1; i++)
		if (men.get(0) == openMenus[i].get(0))
		return;
	openMenus.push(men);
}
